﻿using Learun.Util;
using Learun.Util.SqlSugar;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using DbType = System.Data.DbType;

namespace Learun.Application.Organization
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创建人：研发部
    /// 日 期：2017.03.04
    /// 描 述：岗位管理
    /// </summary>
    public class PostService
    {
        #region 仓储
        Repository<PostEntity> _postRepository => new Repository<PostEntity>();
        #endregion
        #region 构造函数和属性
        private string fieldSql;
        public PostService()
        {
            fieldSql = @"
                    t.F_PostId,
                    t.F_ParentId,
                    t.F_Name,
                    t.F_EnCode,
                    t.F_CompanyId,
                    t.F_DepartmentId,
                    t.F_DeleteMark,
                    t.F_Description,
                    t.F_CreateDate,
                    t.F_CreateUserId,
                    t.F_CreateUserName,
                    t.F_ModifyDate,
                    t.F_ModifyUserId,
                    t.F_ModifyUserName
                    ";
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 获取岗位数据列表（根据公司列表）
        /// </summary>
        /// <param name="companyId">公司主键</param>
        /// <returns></returns>
        public IEnumerable<PostEntity> GetList(string companyId)
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append("SELECT ");
                strSql.Append(fieldSql);
                strSql.Append(" FROM LR_Base_Post t WHERE t.F_DeleteMark = 0 AND t.F_CompanyId =@companyId ORDER BY t.F_DepartmentId,t.F_ParentId,t.F_EnCode ");
                //return this.BaseRepository().FindList<PostEntity>(strSql.ToString(), new { companyId = companyId });
                return SqlSugarHelper.Db.SqlQueryable<PostEntity>(strSql.ToString()).AddParameters(new { companyId = companyId }).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 获取岗位数据列表
        /// </summary>
        /// <param name="companyId">公司主键</param>
        /// <returns></returns>
        public IEnumerable<PostEntity> GetPostList(Pagination paginationobj, string queryJson)
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append("SELECT ");
                strSql.Append(fieldSql);
                strSql.Append(" FROM LR_Base_Post t WHERE t.F_DeleteMark = 0 ");
                var queryParam = queryJson.ToJObject();
                //var dp = new DynamicParameters(new { });
                var dp = new List<SugarParameter>();
                if (!queryParam["keyword"].IsEmpty())
                {
                    dp.Add(new SugarParameter("F_Name", "%" + queryParam["keyword"].ToString() + "%", DbType.String));
                    strSql.Append(" AND t.F_Name LIKE @F_Name ");
                }
                if (!queryParam["ProjectId"].IsEmpty())
                {
                    dp.Add(new SugarParameter("ProjectId", queryParam["ProjectId"].ToString(), DbType.String));
                    strSql.Append("AND t.ProjectId = @ProjectId ");
                }
                else
                {
                    strSql.Append("AND IFNULL(t.ProjectId,'') = '' ");
                }
                strSql.Append(" ORDER BY t.F_EnCode");
                //return this.BaseRepository().FindList<PostEntity>(strSql.ToString(), dp);
                return SqlSugarHelper.Db.SqlQueryable<PostEntity>(strSql.ToString()).AddParameters(dp).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }   /// <summary>
            /// 获取所有岗位数据
            /// </summary>
            /// <param name="companyId">公司主键</param>
            /// <returns></returns>
        public IEnumerable<PostEntity> GetPostListByProjectId(string ProjectId)
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append("SELECT ");
                strSql.Append("t.* , (SELECT COUNT(1)  FROM LR_Base_UserRelation t1 WHERE 1=1 AND IFNULL(t1.ProjectId,'') = @ProjectId AND t1.F_ObjectId = t.F_PostId) AS UserCount");
                strSql.Append(" FROM LR_Base_Post t WHERE t.F_DeleteMark = 0 AND IFNULL(t.ProjectId,'') = @ProjectId ");
                //return this.BaseRepository().FindList<PostEntity>(strSql.ToString(), new { ProjectId = ProjectId });
                return SqlSugarHelper.Db.SqlQueryable<PostEntity>(strSql.ToString()).AddParameters(new { ProjectId = ProjectId }).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 获取岗位数据列表(根据主键串)
        /// </summary>
        /// <param name="postIds">根据主键串</param>
        /// <returns></returns>
        public IEnumerable<PostEntity> GetListByPostIds(string postIds)
        {
            try
            {
                return _postRepository.GetList(t => postIds.Contains(t.F_PostId));
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 获取岗位的实体数据
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        public PostEntity GetEntity(string keyValue) {
            try
            {
                return _postRepository.GetById(keyValue);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        //查找具体项目下公司人员对应的岗位
        public DataTable GetPostByProjectId(string ProjectId)
        {
            string sqlstr = @"SELECT u.F_UserId,p.F_Name FROM lr_base_post p
                            JOIN lr_base_userrelation u
                            ON u.F_Category = 1 AND u.ProjectId = '"+ ProjectId + "' AND u.F_ObjectId = p.F_PostId";
            var data = SqlSugarHelper.Db.Ado.GetDataTable(sqlstr);
            return data;
        }
        /// <summary>
        /// 获取下级岗位id集合
        /// </summary>
        /// <param name="parentIds">父级Id集合</param>
        /// <returns></returns>
        public List<string> GetIdList(List<string> parentIds)
        {
            try
            {
                List<string> res = new List<string>();
                var list = _postRepository.GetList(t => parentIds.Contains(t.F_ParentId));
                foreach (var item in list) {
                    res.Add(item.F_PostId);
                }
                return res;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 虚拟删除
        /// </summary>
        /// <param name="keyValue">主键</param>
        public void VirtualDelete(string keyValue)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                PostEntity entity = new PostEntity()
                {
                    F_PostId = keyValue,
                    F_DeleteMark = 1
                };
                _postRepository.Update(entity);
                SqlSugarHelper.Db.Ado.ExecuteCommand(" Delete  From LR_BASE_USERRELATION where F_OBJECTID = @keyValue  ", new { keyValue = keyValue });

                //db.Delete<UserRelationEntity>(t=>t.F_ObjectId == keyValue);

                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        } 
        /// <summary>
        /// 保存岗位（新增、修改）
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="postEntity">岗位实体</param>
        /// <returns></returns>
        public void SaveEntity(string keyValue, PostEntity postEntity)
        {
            try
            {
                if (!string.IsNullOrEmpty(keyValue))
                {
                    postEntity.Modify(keyValue);
                    _postRepository.Update(postEntity);
                }
                else
                {
                    postEntity.Create();
                    _postRepository.Insert(postEntity);
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }

        } 
        #endregion
    }
}
